#! /usr/bin/env python
# coding=utf-8

import re, sys, settings
from django.db import connection
import pymongo,threading
if '..' not in sys.path:
    sys.path.append('..')

def trim(str):
    return re.sub(r'^\s*|\s*$', '', str)

def judgeIntStr(s):
    try:
        return str(int(s))
    except ValueError:
        return '1'

def getPageNo(request):
    pageNo = request.GET.get('pageNo')
    if not pageNo:
        pageNo = request.POST.get('pageNo', '1')
    pageNo = judgeIntStr(pageNo)
    pageNo = int(pageNo)
    return pageNo
    
def getIntPageNo(pageNo):
    if not pageNo:
        return 1
    pageNo = judgeIntStr(pageNo)
    return int(pageNo)

#过滤html
def filterHtml(content):
    content = re.sub(r'(?msi)<.*?>', '', content)
    content = re.sub(r'&nbsp;', '', content)
    return content

#过滤掉script
def filterScript(content):
    content = re.sub(r'(?msi)<.*?script.*?>', '&lt;script&gt;', content)
    content = re.sub(r'(?msi)</.*?script.*?>', '&lt;script&gt;', content)
    return content

#过滤出空格和换行
def filterBlankNewLine(content):
    result = content
    result = result.replace(' ', '&nbsp;')
    result = result.replace('\n', '<br />')
    return result

#过滤character entity
def filterCharacterEntity(content):
    result = content
    result = result.replace('&', '&amp;')
    result = result.replace('<', '&lt;')
    result = result.replace('>', '&gt;')
    result = result.replace('"', '&quot;')
    return result

#过滤出textarea中的内容安全输出
def safeHtml(content):
    result = content
    result = filterCharacterEntity(result)
    result = filterBlankNewLine(result)
    return result

def getNormalPage(params):
    #生成分页对象
    pageNo = params['pageNo']
    pageSize = params['pageSize']
    totalResults = params['totalResults']
    pageCount = totalResults / pageSize
    if totalResults % pageSize != 0:
        pageCount += 1
    #是否输出第一页
    isOutputPre = pageNo > 1
    #起始输出页
    begin = max(1, pageNo - 3)
    #终止输出页
    end = min(max(pageNo, pageNo + 2, begin + 5), pageCount)
    if end - begin < 5:
        begin = max(min(begin, end - 5), 1)
    #更多标记
    isOutputMore = end < pageCount
    #是否输出下一页
    isOutputNext = pageNo < pageCount
    page = {
        'pageNo': pageNo,
        'pageCount': pageCount,
        'pageSize': pageSize,
        'totalResults': totalResults,
        'items': params['items'],
        'isOutputPre': isOutputPre,
        'prePageNo': pageNo - 1,
        'beginEnd': range(begin, end + 1),
        'isOutputMore': isOutputMore,
        'isOutputNext': isOutputNext,
        'nextPageNo': pageNo + 1
        }
    return page

def quoteEscape(text):
    return text.replace("'", r"\'").replace('"', '\"').replace('%', '\%')

def repl(m):
    if m:
        return m.group(1)
    return ''

def convertSqlByParam(sql, param):
    result = sql
    for item in param.keys():
        result = re.sub(r'(?msi)<%s>(.*?)</%s>' % (item, item), repl, result)
    li = re.findall(r'<(\w+)>', result)
    for item in li:
        result = re.sub(r'(?msi)<%s>(.*?)</%s>' % (item, item), '', result)
    if result.find(':SORT') > -1 and param.get('sort'):
        result = result.replace(':SORT_ORDER', quoteEscape(param.get('sortOrder')))
        result = result.replace(':SORT', quoteEscape(param.get('sort')))

    return result
    
def getTraceId():
    return str(int(getIncrementId('traceIdGeneratorId')))
#    traceObj = TraceIdGenerator()
#    traceObj.save()
#    return str(traceObj.id)

def getIncrementId(idName):
    mongoDB = getThreadLocalMongoDB()['mongoDB']
    seq = mongoDB.counters.find_and_modify(query={'_id': idName}, update={'$inc': {'c': 1}})
    return int(seq['c'])

def getParamFromRequest(reqDict):
    result = {}
    for k,v in reqDict.items():
        if v:
            result[k] = v
    return result

def getParamFromRequestExceptTraceId(reqDict):
    result = {}
    for k,v in reqDict.items():
        if k != 'traceId' and v:
            result[k] = v
    return result
    
def putFormData(request, formName):
    formData = getParamFromRequestExceptTraceId(request.REQUEST)
    traceId = request.REQUEST.get('traceId')
    if traceId and request.session.get(traceId):
        request.session[traceId][formName] = formData
    else:
        traceId = getTraceId()
        request.session[traceId] = {}
        request.session[traceId][formName] = formData
        # though traceId have been set in filter, if must init here for first time, otherwise traceId wouldn't have value
        request.traceId = traceId
    return formData

def getParamByTraceId(request, formName):
    if request.method == 'GET':
        traceId = request.GET.get('traceId')
        if traceId:
            if request.session.get(traceId):
                return request.session[traceId].get(formName)
        return None
    return putFormData(request, formName)

def convert2Unicode(d):
    result = {}
    
    for k,v in d.items():
        k = convertStr2Unicode(k)
        v = convertStr2Unicode(v)
        result[k] = v

    return result

def convert2Utf8(d):
    result = {}
    
    for k,v in d.items():
        if type(k).__name__ == 'unicode':
            k = k.encode('utf8')
        if type(v).__name__ == 'unicode':
            v = v.encode('utf8')
        result[k] = v

    return result

def convertStr2Unicode(text):
    result = text
    if type(result).__name__ == 'str':
        try:
            result = unicode(result, 'utf8')
        except UnicodeDecodeError:
            result = unicode(result, 'gbk')
    return result

threadLocal = threading.local()

def getThreadLocalMongoDB():
    if not hasattr(threadLocal, 'mongoDict'):
        con = pymongo.Connection(settings.MONGODB_HOST, settings.MONGODB_PORT)
        if settings.MONGODB_USER:
            con['jcodemanage'].authenticate(settings.MONGODB_USER, settings.MONGODB_PASSWORD)
        threadLocal.mongoDict = {
            'mongoDB': con['jcodemanage'],
            'con': con
        }
    return threadLocal.mongoDict
        
def closeThreadLocalMongoDB():
    if hasattr(threadLocal, 'mongoDict'):
        threadLocal.mongoDict['con'].disconnect()
        del threadLocal.mongoDict

def getAppKey(appKey):
    if appKey == settings.TAOBAO_APP_KEY:
        return appKey
    if appKey == settings.TAOBAO_APP_KEY_CHAT:
        return appKey
    if appKey == settings.TAOBAO_APP_KEY_BACK:
        return appKey
    if appKey == settings.TAOBAO_APP_KEY_FRONT:
        return appKey
    if appKey == settings.ADMIN_APP_KEY:
        return appKey
    if not appKey:
        return settings.TAOBAO_APP_KEY
    raise Exception('not property input param appKey:%s' % (appKey))

def getAppKeyFromRequest(request):
    if request.session.get('resStruct'):
        return getAppKey(request.session['resStruct'].get('app_key'))
    return settings.TAOBAO_APP_KEY

def initParam(request, formName, result, paramMap, pageObj):
    requestParam = getParamByTraceId(request, formName)
    if requestParam:
        result.update(requestParam)
        paramMap.update(requestParam)
        
    if requestParam and requestParam.get('pageNo'):
        pageObj['pageNo'] = getIntPageNo(requestParam['pageNo'])
    else:
        pageObj['pageNo'] = getPageNo(request)
    pageObj['pageSize'] = settings.PAGE_SIZE
    pageObj['begin'] = (pageObj['pageNo'] - 1) * pageObj['pageSize']
    pageObj['end'] = pageObj['pageNo'] * pageObj['pageSize']

if __name__ == '__main__':
    pass

